<?php

namespace app\api\controller\ykjp\sell;

use app\common\controller\Api;

/**
 * 采购录单
 *
 * @icon fa fa-circle-o
 */
class Sell extends Api {

    protected $model = null;
    protected $noNeedRight = '*';

    public function _initialize() {
        parent::_initialize();
    }


    /**
     * 销售录单
     */
    public function addSell() {

        $sellModel = new \app\admin\model\ykjp\sell\Sell;

        $param = input('post.');
        $row = [
            'code' => "YK" . date("ymdHis", time()) . rand(1000, 9999),
            'customer_info_id' => $param['customer_info_id'],
            'customer_name' => $param['customer_name'],
            'linkman' => $param['linkman'],
            'phone' => $param['phone'],
            'delivery_time' => $param['delivery_time'],
            'type' => $param['type'],
            'total_nums' => $param['total_nums'],
            'city' => $param['city'],
            'address' => $param['address'],
            'rate' => $param['rate'],
            'real_money' => $param['real_money'],
            'admin_id' => $this->auth->id,
            'theory_money' => $param['theory_money'],
            'remark' => $param['remark'],
            'billing_time' => time(),
            'createtime' => time(),
            'status_list' =>5,
            'updatetime' => time(),
        ];

        $isnter = $sellModel->insertGetId($row);
        $param['product_price'] = explode(',',$param['product_price']);
        $param['product_id'] = explode(',',$param['product_id']);
        $param['product_nums'] = explode(',',$param['product_nums']);
        $param['product_remarks'] = explode(',',$param['product_remarks']);
        $param['product_unit'] = explode(',',$param['product_unit']);
        $param['product_wait_nums'] = explode(',',$param['product_wait_nums']);

        $sellProduct = new \app\admin\model\ykjp\sell\Product;
        if ($isnter) {
            foreach ( $param['product_price'] as $k=>$v) {
               $sellProduct->insert([
                    'sell_id'  =>  $isnter,
                    'product_id' =>  $param['product_id'][$k],
                    'price' =>  $param['product_price'][$k],
                    'nums' =>  $param['product_nums'][$k],
                    'subtotal' =>  $param['product_price'][$k] * $param['product_nums'][$k],
                    'unit' =>  $param['product_unit'][$k],
                    'remarks' =>  $param['product_remarks'][$k],
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }

            $this->success('保存成功');
        }

        $this->error('保存失败');
    }

    /**
     * 查看
     */
    public function index() {

        $sellModel = new \app\admin\model\ykjp\sell\Sell;
        $info = $sellModel->order('createtime desc')->where('deletetime',null)->where('status_list','>=',1)->select();
        $this->success('返回成功',['data' => $info]);

        $date = date("Y-m-d", time());
        $this->assign("date", $date);
        if ($this->request->isAjax()) {
            $a = $this->request->get('a');
            if ($a == 1) {
                //点击获取客户信息
                $this->model = new \app\admin\model\ykjp\information\basisinfo\Customerinfo;
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->where('firmid', $this->auth->firmid)
                        ->order($sort, $order)
                        // ->field("name,contact,phone,description,id")
                        ->count();
                $list = $this->model
                        ->where($where)
                        ->where('firmid', $this->auth->firmid)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->field("name,contact,phone,description,id,status")
                        ->select();
                $list = collection($list)->toArray();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            } else {
                //点击获取商品信息
                $this->model = new \app\admin\model\ykjp\product\Product;
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->where('inventory', '>', 0)
                        ->where('firmid', $this->auth->firmid)
                        ->order($sort, $order)
                        ->count();
                $list = $this->model
                        ->where($where)
                        ->where('inventory', '>', 0)
                        ->where('firmid', $this->auth->firmid)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }
        }
        return $this->view->fetch();
    }

    /**
     * 查看订单详情
     */
    public function orderDetail() {
        $OrderModel = new \app\admin\model\ykjp\sell\Sell;
        $ProductModel = new \app\admin\model\ykjp\sell\Product;

        $param = input('post.');

        if (empty($param['id'])) {
            $this->error('单号ID未知');
        }

        $orderinfo = $OrderModel->where('id',$param['id'])->find();
        $orderinfo['productlist'] = $ProductModel->where('sell_id',$param['id'])->select();

        foreach ( $orderinfo['productlist'] as $k=>$v) {
            $v['info'] = Db('ykjp_product')->where('id',$orderinfo['productlist'][$k]['product_id'])->find();

            if (!empty($v['info']['image'])) {
                $v['url'] = $this->request->scheme() . "://".$_SERVER["HTTP_HOST"] .$v['info']['image'];
            }
        }

        $this->success('返回成功',['data' => $orderinfo]);

    }
	
    /**
     * 获取客户详情
     */
    public function getCustomerByid($ids) {
        $this->model = new \app\admin\model\ykjp\information\basisinfo\Customerinfo;
        $row = $this->model->get(['id' => $ids, "firmid" => $this->auth->firmid]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $city = "";
            if ($row) {
                $row = $row->toArray();
                if (isset($row['city']) && $row['city'] != "") {
                    $city = explode('/', $row['city']);
                }
            }
            $this->success(null, null, ['row' => $row, "city" => $city]);
        }
        $this->error(__('No Results were found'));
    }

    /**
     * 获取产品详情
     */
    public function getProductByid($ids) {
        $this->model = new \app\admin\model\ykjp\product\Product;
        $row = $this->model->get(['id' => $ids, "firmid" => $this->auth->firmid]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $city = "";
            if ($row) {
                $row = $row->toArray();
            }
            $this->success(null, null, ['row' => $row]);
        }
        $this->error(__('No Results were found'));
    }


}
